import wxValidate from 'wechat-validate'
Page({
  behaviors: [wxValidate],
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    name: '',
    gender: 1,
    mobile: '',
    houseId: '',
    visitDate: '',
    currentDate: +new Date(),
    maxDate: +new Date() + 1000 * 60 * 60 * 24 * 3
  },
  onLoad() {
    // 获取房屋列表
    this.getHouseList()
  },
  rules: {
    name: [
      {required: true, message: '访客姓名不能为空!'},
      {pattern: /[\u4e00-\u9fa5]{2,5}/, message: '访客姓名只能为中文!'},
    ],
    mobile: [
      {required: true, message: '访客手机号不能为空!'},
      {pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!'},
    ],
    houseId: [
      {required: true, message: '请选择到访的房屋!'}
    ],
    visitDate: [
      {required: true, message: '请选择到访的日期!'}
    ],
  },
  // 获取房屋列表
  async getHouseList() {
    // 调用接口
    const { code, data: houseList } = await wx.http.get('/house')
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast()
    // 渲染数据
    this.setData({houseList})
  },
  // 获取用户选择的房屋
  selectHouseInfo(ev) {
    // 记录获取的数据
    this.setData({
      houseId: ev.detail.id,
      houseInfo: ev.detail.name,
    })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },

  selectDate(e) {
    // console.log(e.detail)
    this.setData({
      visitDate: wx.utils.formatDate(e.detail),
      dateLayerVisible: false
    })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  async goPassport() {
    if (!this.validate()) return
    // 发请求提交数据
    const { houseId, name, gender, mobile, visitDate } = this.data
    const { code, data } = await wx.http.post('/visitor', { houseId, name, gender, mobile, visitDate })
    if (code !== 10000) return wx.utils.toast('提交失败')
    // console.log(data)
    wx.redirectTo({
      url: '/visitor_pkg/pages/passport/index?id=' + data.id,
    })
  },
})
